package com.itts.middle.config.expection;

import com.itts.common.exception.CommonException;
import com.itts.common.util.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName GlobalExceptionHandler
 * @Description
 * @Author zslme
 * @Date2020/3/15 21:07
 **/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {



    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map bizExceptionHandler(HttpServletRequest req, Exception e){
        log.error("服务器运行异常",e);
        Map map = new HashMap(3);
        map.put("code", 500);
        map.put("msg", "服务器运行异常");
        map.put("flag", false);
        return map;
    }



    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return R.error(objectError.getDefaultMessage());
    }

    @ExceptionHandler(CommonException.class)
    @ResponseBody
    public Map commonExceptionHandler(CommonException e){
        log.error("通用异常",e.getErrMsg());
        Map map = new HashMap(3);
        map.put("code", 500);
        map.put("msg", e.getErrMsg());
        map.put("flag", false);
        return map;
    }
}
